import 'package:get/get.dart';

class WorkerTestController extends GetxController {
  /// 可观察状态
  final count = 0.obs;
  final searchKeyword = ''.obs;

  /// 集中管理 worker，方便释放
  final List<Worker> _workers = [];

  @override
  void onInit() {
    super.onInit();

    // 1. ever: 每次 count 变化都触发
    _workers.add(
      ever<int>(count, (value) {
        print("【ever】count变化 => $value");
      }),
    );

    // 2. once: 只触发一次
    _workers.add(
      once<int>(count, (value) {
        print("【once】count第一次变化 => $value");
      }),
    );

    // 3. interval: 节流，每隔1秒只触发一次
    _workers.add(
      interval<int>(count, (value) {
        print("【interval】节流1s => $value");
      }, time: const Duration(seconds: 1)),
    );

    // 4. debounce: 防抖，输入停止500ms后触发
    _workers.add(
      debounce<String>(searchKeyword, (value) {
        print("【debounce】搜索触发 => $value");
      }, time: const Duration(milliseconds: 500)),
    );
  }

  /// 模拟点击按钮
  void increment() {
    count.value++;
  }

  /// 模拟搜索输入
  void onSearchChanged(String keyword) {
    searchKeyword.value = keyword;
  }

  @override
  void onClose() {
    // 页面销毁时释放所有 worker
    for (final worker in _workers) {
      worker.dispose();
    }
    _workers.clear();
    print("✅ 所有 Worker 已释放");
    super.onClose();
  }
}
